<template>
  <el-card>
    <el-form :inline="true" class="form">
      <el-form-item label="职位搜索">
        <el-input
          placeholder="请你输入搜索职位关键字"
          v-model="keyword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          :disabled="keyword ? false : true"
          @click="search"
          >搜索</el-button
        >
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" icon="Plus" @click="addRole"
      >添加职位</el-button
    >
    <el-table border style="margin: 10px 0px" :data="allRole">
      <el-table-column type="index" align="center" label="#"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="职位名称"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建世间"
        align="center"
        show-overflow-tooltip
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        show-overflow-tooltip
        prop="updateTime"
      ></el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <!-- row:已有的职位对象 -->
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="setPermisstion(row)"
            >分配权限</el-button
          >
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateRole(row)"
            >编辑</el-button
          >
          <el-popconfirm
            :title="`你确定要删除${row.roleName}?`"
            width="260px"
            @confirm="removeRole(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 20, 30, 40]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHasRole"
      @size-change="sizeChange"
    />
  </el-card>
  <!-- 添加职位与更新已有职位的结构:对话框 -->
  <el-dialog
    v-model="dialogVisite"
    :title="RoleParams.id ? '更新职位' : '添加职位'"
  >
    <el-form :model="RoleParams" :rules="rules" ref="form">
      <el-form-item label="职位名称" prop="roleName">
        <el-input
          placeholder="请你输入职位名称"
          v-model="RoleParams.roleName"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="default" @click="dialogVisite = false"
        >取消</el-button
      >
      <el-button type="primary" size="default" @click="save">确定</el-button>
    </template>
  </el-dialog>
  <!-- 抽屉组件:分配职位的菜单权限与按钮的权限 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单与按钮的权限</h4>
    </template>
    <template #default>
      <!-- 树形控件 -->
      <el-tree
        :data="menuArr"
        ref="tree"
        show-checkbox
        node-key="id"
        default-expand-all
        :props="defaultProps"
        :default-checked-keys="selectArr"
      />
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="handler">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import {reqAllRoleList,reqAddOrUpdateRole,reqAllMenuList,reqSetPermisstion,reqRemoveRole} from "@/api/acl/role/index"
import {RoleResponseData,Records,RoleData,MenuList,MenuResponseData} from "@/api/acl/role/type"
import useLayOutSettingStore from '@/store/modules/setting'
import { ElMessage } from "element-plus";
let settingStore = useLayOutSettingStore()
let keyword = ref<string>("");
let pageNo = ref<number>(1);
let pageSize = ref<number>(5);
let total = ref<number>(0);
let dialogVisite = ref<boolean>(false)
let drawer = ref<boolean>(false)
let rules={}
let menuArr = ref<MenuList>([])
//准备一个数组:数组用于存储勾选的节点的ID(四级的)
let selectArr = ref<any>([]);
const defaultProps = {
  children: 'children',
  label: 'name',
}
//收集新增岗位数据
let RoleParams = reactive<RoleData>({
    roleName: ''
})
//存储全部已有的职位
let allRole = ref<Records>([]);
let tree =ref<any>()
//组件挂载完毕
onMounted(() => {
    //获取职位请求
    getHasRole();
});
//获取全部用户信息的方法|分页器当前页码发生变化的回调
const getHasRole = async (pager = 1) => {
    //修改当前页码
    pageNo.value = pager;
    let result: RoleResponseData = await reqAllRoleList(pageNo.value, pageSize.value, keyword.value);
    if (result.code == 200) {
        total.value = result.data.total;
        allRole.value = result.data.records;
    }
}
// 添加职位
const addRole = ()=>{
  Object.assign(RoleParams,{
    roleName: '',
    id:0
  })
  dialogVisite.value = true
}
// 编辑
const updateRole = (row:Records)=>{
  Object.assign(RoleParams,row)
  dialogVisite.value = true
}
// 保存
const save= async ()=>{
  let res = await reqAddOrUpdateRole(RoleParams)
  if(res.code==200){
    ElMessage({type:'success',message:RoleParams.id?'修改成功':'新增成功'})
    dialogVisite.value = false
    getHasRole(RoleParams.id?pageNo.value:1)
  }else{
    ElMessage({type:'success',message:RoleParams.id?'修改失败':'新增失败'})
  }
}
const sizeChange = ()=>{
  getHasRole();
}
// 分配权限
const setPermisstion= async (row:RoleData)=>{
  Object.assign(RoleParams, row);
  let res:MenuResponseData = await reqAllMenuList((RoleParams.id as number))
  if(res.code==200){
    menuArr.value = res.data
    drawer.value = true
    selectArr.value = filterSelectArr(menuArr.value,[])
  }
}
// 筛选出已经勾选的id
const filterSelectArr = (allData:any,initArr:any)=>{
  allData.forEach((item:any) => {
    if(item.select&&item.level==4){
      initArr.push(item.id)
    }
    if(item.children&&item.children.length>0){ 
      filterSelectArr(item.children,initArr)
    }
  });
  return initArr;
}
//确定
const handler = async ()=>{
  // 全选中的数组
  let selectVal = tree.value.getCheckedKeys()
  // 半选中的数组
  let selectVal2 = tree.value.getHalfCheckedKeys()
  let permissionId = selectVal.concat(selectVal2)
  let res:any = await reqSetPermisstion((RoleParams.id as number),permissionId)
  if(res.code==200){
    ElMessage({type:'success',message:'分配成功'})
    drawer.value = false
    getHasRole(pageNo.value);
    window.location.reload()
  }
}
// 删除
const removeRole = async (id:number)=>{
  let res = await reqRemoveRole(id)
  if(res.code==200){
    ElMessage({type:'success',message:'删除成功'})
    getHasRole(menuArr.value.length>0?pageNo.value:pageNo.value-1);
  }
}
// 搜索
const search = () => {
  getHasRole();
  keyword.value = "";
};
// 重置
const reset = () => {
  settingStore.refsh = !settingStore.refsh;
};
</script>

<style lang="scss" scoped></style>
